package ace.module.oss.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.AbstractSpringDtoManager;
import ace.cmp.i18n.api.MessageSourceAssertService;
import ace.module.oss.api.model.dto.OssApplicationConfigDto;
import ace.module.oss.core.impl.dao.entity.OssApplicationConfig;
import ace.module.oss.core.impl.dao.repository.OssApplicationConfigRepository;
import ace.module.oss.core.impl.manager.OssApplicationConfigManager;
import ace.module.oss.core.impl.properties.OssCoreProperties;
import java.time.Instant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * oss应用配置 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class OssApplicationConfigManagerImpl
    extends AbstractSpringDtoManager<OssApplicationConfig, Long, OssApplicationConfigDto>
    implements OssApplicationConfigManager {

  private final OssApplicationConfigRepository ossApplicationConfigRepository;
  private final MessageSourceAssertService assertService;
  private static final Long DEFAULT_ID = Long.MAX_VALUE - 1;
  private final OssCoreProperties ossCoreProperties;

  @Override
  public OssApplicationConfig getByOssAppIdAndKeyAndDeleteFlagIsFalse(Long ossAppId, String key) {
    return this.ossApplicationConfigRepository.getByOssAppIdAndKeyAndDeleteFlag(
        ossAppId, key, CoreConstant.DELETE_FLAG_NOT);
  }

  @Override
  public OssApplicationConfig getOrSystemDefaultByOssAppIdAndKeyAndDeleteFlagIsFalse(
      Long ossAppId, String key) {
    OssApplicationConfig config = this.getByOssAppIdAndKeyAndDeleteFlagIsFalse(ossAppId, key);
    if (config == null) {
      return this.getSystemDefault(ossAppId, key);
    }
    return config;
  }

  @Override
  public OssApplicationConfig getSystemDefault(Long ossAppId, String key) {
    return OssApplicationConfig.builder()
        .id(DEFAULT_ID)
        .catalog(ossCoreProperties.getDefaultCatalog())
        .ossAppId(ossAppId)
        .key(key)
        .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
        .createTime(Instant.now().toEpochMilli())
        .updateTime(Instant.now().toEpochMilli())
        .rowVersion(CoreConstant.DEFAULT_ROW_VERSION)
        .build();
  }
}
